<?php
namespace Home\Controller;

/**
 * 接口函数
 * ApiController
 */
class ApiController extends BaseController {

    const SUCC_CODE = 0;
    const FAIL_CODE = -1;

    /**
     * 获取小说列表
     */
    public function novel_list(){
        $Novel_Model = M('novel');
        $where = [];

        //关键字搜索
        $keyword = trim(I('post.keyword'));
        if($keyword != ''){
            $where['title'] = ['like',"%$keyword%"];

            //搜索次数+1
            $Novel_Model->where(['title'=>$keyword])->setInc('search_number');
        }

        //排序
        $order_sort = I('post.order_sort')?I('post.order_sort'):'desc';
        $order_field = I('post.field')?I('post.field'):'read_number';
        $order_by[$order_field] = $order_sort;

        $class_id = I('post.class_id')?I('post.class_id'):'';      //小说类型
        $fit_crowd = I('post.fit_crowd');    //合适人群
        $is_finish = I('post.is_finish');    //是否完结
        $is_recommend = I('post.is_recommend');    //是否推荐
        $device_sn = I('post.device_sn');          //用户编号
        $rank_tags = I('post.rank_tags');          //排行榜标签


        $sort_arr = I('post.sort_arr');     //组合查询
//        $sort_arr = [['field'=>"create_time",'value'=>1],['field'=>"is_finish",'value'=>4],['field'=>"word_arr_id",'value'=>6],['field'=>"search_item_id",'value'=>9]];


        if($sort_arr && $sort_arr != []){
            //查询数组按健名value值排序
            // $search_arr = $this->array_sort($sort_arr,'value');
            $search_arr = $sort_arr;
            foreach($search_arr as $val){
                if($val['field'] == 'create_time' && $val['value'] != 0){
                    $order_by['create_time'] = 'desc';
                }else if($val['field'] == 'read_number' && $val['value'] != 0){
                    $order_by['read_number'] = 'desc';
                }

                if($val['field'] == 'is_finish' && $val['value'] != 0){
                    $order_by['is_finish'] = 'desc';
                }else if($val['field'] == 'is_serial' && $val['value'] != 0){
                    $order_by['is_serial'] = 'desc';
                }

                if($val['field'] == 'word_arr_id' && $val['value'] != 0){
                    $where['word_arr_id'] = $val['value'];
                }

                if($val['field'] == 'search_item_id' && $val['value'] != 0){
                    $where['search_item_id'] = $val['value'];
                }
            }
        }

        $search_item_id = I('post.search_item_id');   //组合筛选时，搜索分类ID
        $word_arr_id = I('post.word_arr_id');         //组合筛选时，字数组ID

        if($search_item_id){
            $where['search_item_id'] = $search_item_id;
        }

        if($word_arr_id){
            $where['word_arr_id'] = $word_arr_id;
        }

        if($rank_tags){
            $where['rank_tags'] = $rank_tags;
        }
        if($device_sn){
            $novel_ids = M('readrecord')->where(['device_sn'=>$device_sn,'is_del'=>0,'is_bookrack'=>1])->field('novel_id')->select();
            foreach($novel_ids as $val){
                $novel_arr[] = $val['novel_id'];
            }

            $where['id'] = ['in',$novel_arr];
        }
        if($fit_crowd){
            $where['fit_crowd'] = $fit_crowd;
        }

        if($is_finish){
            $where['is_finish'] = $is_finish;
        }

        if($is_recommend){
            $where['is_recommend'] = $is_recommend;
        }
        $class_name = null;
        if($class_id != ''){
            $where['class_id'] = $class_id;
            $class_name = M('class')->getfieldbyid($class_id,'class_name');
        }

        $where['is_del'] = 0;
        $where['is_pass'] = 1;

        $offset = I('post.offset',0,'intval');
        $limit = I('post.limit',100,'intval');

        $list = $Novel_Model->where($where)->order($order_by)->limit($offset,$limit)->select();
        foreach($list as $key=>$val){
            $is_collect = $this->is_collect_novel($val['id']);
            if($is_collect == 0){
                $list[$key]['is_collect'] = 1;
            }else{
                $list[$key]['is_collect'] = 0;
            }

            if(!(strpos($val['cover'],'http://') === 0)){
                $list[$key]['cover'] = 'http://'.$_SERVER['HTTP_HOST'].$val['cover'];
            }
            $list[$key]['create_time'] = date('Y-m-d',$val['create_time']);
            $list[$key]['words_number'] = $this->number_to_word($val['words_number']);
            $list[$key]['collect_number'] = $this->number_to_word($val['collect_number']);
            $list[$key]['read_number'] = $this->number_to_word($val['read_number']);
            $list[$key]['label'] = $this->str_to_arr($val['label']);                      //标签

            $chapter_number = M('chapter')->where(['novel_id'=>$val['id']])->count();
            $list[$key]['chapter_number'] = $chapter_number;                      //总章数字

            //未读章节
            $is_read = M('readrecord')->where(['device_sn'=>$this->uid,'novel_id'=>$val['id']])->find();
            if($is_read){
                $novel_chapter = M('chapter')->where(['id'=>$is_read['chapter_id']])->find();
                $list[$key]['not_read_number'] = $chapter_number - $novel_chapter['novel_chapter'];
            }

        }

        if($class_name){
            $this->ajaxReturn(['code'=>self::SUCC_CODE,'list'=>$list?$list:[],'class_name'=>$class_name]);            
        }else{
            $this->ajaxReturn(['code'=>self::SUCC_CODE,'list'=>$list?$list:[]]);
        }

    }


    //小说详情
    public function novel_info(){
        $novel_Model = M('novel');
        $chapter_Model = M('chapter');
        $id = I('post.id');
        $type = I('post.type');   // 0小说基本信息  1小说基本信息跟全部章节基本信息  2小说某章节信息


        if(!isset($id)){
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"参数错误！"]);
        }

        $novel_info = $novel_Model->where(['id'=>$id])->find();
        if(!(strpos($novel_info['cover'],'http://') === 0)){
            $novel_info['cover'] = 'http://'.$_SERVER['HTTP_HOST'].$novel_info['cover'];

            $is_collect = $this->is_collect_novel($novel_info['id']);
            if($is_collect == 0){
                $novel_info['is_collect'] = 1;
            }else{
                $novel_info['is_collect'] = 0;
            }

            $novel_info['words_number'] = $this->number_to_word($novel_info['words_number']);
            $novel_info['collect_number'] = $this->number_to_word($novel_info['collect_number']);
            $novel_info['read_number'] = $this->number_to_word($novel_info['read_number']);
            $novel_info['label'] = $this->str_to_arr($novel_info['label']);
            $novel_info['chapter_number'] = M('chapter')->where(['novel_id'=>$novel_info['id']])->count();                      //总章节数

            //未读章节
            $is_read = M('readrecord')->where(['device_sn'=>$this->uid,'novel_id'=>$id])->find();
            if($is_read){
                $novel_chapter = M('chapter')->where(['id'=>$is_read['chapter_id']])->find();
                $novel_info['not_read_number'] = $novel_info['chapter_number'] - $novel_chapter['novel_chapter'];
            }
        }

        $novel_chapters = $chapter_Model->where(['novel_id'=>$id])->order('chap_num asc')->select();

        // C('LAYOUT_ON',false);
        // $novel_chapter_html_arr = [];
        // foreach($novel_chapters as $item){
        // $this->assign('chapter',$item);
        //     $novel_chapter_html_arr[] = $this->fetch('novel_info');
        // }
        $novel_chapter_html_arr = $novel_chapters;
        foreach($novel_chapter_html_arr as $k=>$v){
            // $novel_chapter_html_arr[$k]['title'] = "<h3>{$v['title']}</h3>";
            $novel_chapter_html_arr[$k]['content'] = "<h3>{$v['title']}</h3>" . "<p>{$v['content']}</p>";
        }
        if($type == 0){
            $data['novel_info'] = $novel_info;
        }else if($type == 1){
            $data['novel_info'] = $novel_info;
            $data['chapter_info'] = $novel_chapter_html_arr;
        }else if($type == 2){
           //根据记录表查询  章节信息
            $is_read = M('readrecord')->where(['novel_id'=>$id,'device_sn'=>$this->uid])->find();
            if($is_read){
                $chapter_info = M('chapter')->where(['id'=>$is_read['chapter_id']])->find();
                $chapter_info['percent'] = $is_read['percent'];
                $chapter_info['words_number'] = $this->number_to_word($chapter_info['words_number']);
            }
            $data['novel_info'] = $novel_info;
            $data['chapter_info'] = $chapter_info;
        }

        if($data){
            $this->ajaxReturn(['code'=>self::SUCC_CODE,'data'=>$data]);
        }else{
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"数据有误，稍后请重试！"]);
        }
    }

    //小说进度  继续阅读
    public function read_continue(){
        $read_record_Model = M('readrecord');

        $novel_id = I('post.novel_id');
        $chapter_id = I('post.chapter_id');

        if(!isset($novel_id) || !isset($chapter_id) || empty($novel_id) || empty($chapter_id)){
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"参数错误，请重试"]);
        }
        $uid = $this->uid;

        $where['novel_id'] = $novel_id;
        $where['chapter_id'] = $chapter_id;
        $where['device_sn']= $uid;
        $read_record_info = $read_record_Model->where($where)->find();
        if($read_record_info){
            $this->ajaxReturn(['code'=>self::SUCC_CODE,'message'=>"获取成功",'read_record_info'=>$read_record_info]);
        }else{
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"数据获取失败，稍后请重试"]);
        }
    }

    //用户有没有上架某小说
    public function user_is_collect_novel(){
        $novel_id = I('post.id');
        $is_collect = $this->is_collect_novel($novel_id);

        if($is_collect == -1){
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"未加入书架"]);
        }else{
            $this->ajaxReturn(['code'=>self::SUCC_CODE,'message'=>"已经在书架上"]);
        }
    }

    //添加新书到书架
    public function collect_novel(){
        $novel_Model = M('novel');
        $read_record_Model = M('readrecord');
        $id = I('post.id');

        if(!isset($id) || empty($id)){
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"参数有误，稍后请重试！"]);
        }

        $is_collect = $this->is_collect_novel($id);

        if($is_collect == -1){
            $is_read = $this->is_read_novel($id);  //判断有没有阅读记录

            if($is_read == 0){
                $where['device_sn'] = $this->uid;
                $where['novel_id'] = $id;
                $result = $read_record_Model->where($where)->save(['is_bookrack'=>1]);
            }else{
                //没有阅读记录
                $data['novel_id'] = $id;
                $data['device_sn'] = $this->uid;
                $data['is_bookrack'] = 1;
                $data['update_time'] = time();
                $result = $read_record_Model->add($data);
            }

            if($result){
                //小说收藏数+1
                $novel_Model->where(['id'=>$id])->setInc('collect_number');
                $this->ajaxReturn(['code'=>self::SUCC_CODE,'message'=>"已成功添加到书架"]);
            }else{
                $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"添加失败，稍后请重试！"]);
            }
        }else{
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"此书已经在书架上！"]);
        }
    }


    //从书架下架
    public function cancel_novel(){
        $novel_Model = M('novel');
        $read_record_Model = M('readrecord');

        $id = I('post.id');

        if(!isset($id) || empty($id)){
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"参数有误，稍后请重试！"]);
        }

        $result = $read_record_Model->where(['device_sn'=>$this->uid,'novel_id'=>$id])->save(['is_bookrack'=>0]);
        if($result){
            //小说收藏数-1
            $novel_Model->where(['id'=>$id])->setDec('collect_number');
            $this->ajaxReturn(['code'=>self::SUCC_CODE,'message'=>"已成功从书架中移除"]);
        }else{
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"操作失败，稍后请重试！"]);
        }
    }


    //类型列表
    public function class_list(){
        $class_Model = M('class');
        $novel_Model = M('novel');

        $where = [];

        //关键字搜索
        $keyword = I('post.keyword');
        $fit_crowd = I('post.fit_crowd');    //男频还是女频 1表示男  2表示女


        if($keyword != ''){
            $where['class_name'] = ['like',"%$keyword%"];
        }

        //根据男频、女频类型搜索
        if($fit_crowd != 0 && $fit_crowd != '' && $fit_crowd != null){
            $class_ids = $novel_Model->where(['fit_crowd'=>$fit_crowd])->Field('class_id')->select();
            foreach($class_ids as $val){
                $class_arr[] = $val['class_id'];
            }

            $class_arr = array_unique($class_arr);
            $where['id'] = ['in',$class_arr];
        }

        $where['is_del'] = 0;

        $offset = I('post.offset',0,'intval');
        $limit = I('post.limit',100,'intval');

        $list = $class_Model->where($where)->limit($offset,$limit)->select();
        foreach($list as $key=>$val){
            $list[$key]['novel_number'] = $this->class_novel_number($val['id']);

            if($val['cover_pic']){
                if(!(strpos($val['cover_pic'],'http://') === 0)){
                    $list[$key]['cover_pic'] = 'http://'.$_SERVER['HTTP_HOST'].$val['cover_pic'];
                }
            }
        }

        $this->ajaxReturn(['code'=>self::SUCC_CODE,'list'=>$list?$list:[]]);
    }


    //阅读记录写入数据表
    public function read_record(){
        $read_record_Model = M('readrecord');

        $novel_id = I('post.novel_id');
        $chapter_id = I('post.chapter_id');
        $percent = I('post.percent');         //不大于1的小数，保留两位

        if(!isset($novel_id) || !isset($chapter_id) || empty($novel_id) || empty($chapter_id)){
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"参数错误，请重试"]);
        }

        $data['novel_id'] = $novel_id;
        $data['chapter_id'] = $chapter_id;
        $data['percent'] = $percent;
        $data['device_sn'] = $this->uid;
        $data['update_time'] = time();

        $is_read = $read_record_Model->where(['novel_id'=>$novel_id,'chapter_id'=>$chapter_id,'device_sn'=>$this->uid])->getField('id');
        if($is_read){
            $result = $read_record_Model->where(['id'=>$is_read])->save($data);
        }else{
            $result = $read_record_Model->add($data);

            //小说表阅读人数+1
            M('novel')->where(['id'=>$novel_id])->setInc('read_number');
        }

        if($result){
            $this->ajaxReturn(['code'=>self::SUCC_CODE]);
        }else{
            $this->ajaxReturn(['code'=>self::FAIL_CODE]);
        }
    }


    //反馈问题配置列表
    public function feed_back_config(){
        $feed_back_config_Model = M('feedback_config');
        $list = $feed_back_config_Model->select();
        $this->ajaxReturn(['code'=>self::SUCC_CODE,'list'=>$list?$list:[]]);
    }


    //用户反馈
    public function add_feed_back(){
        $feed_back_Model = M('feedback');
        $uid = $this->uid;

        $config_id = I('post.config_id');

        if(!isset($config_id) || empty($config_id)){
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"参数有误！"]);
        }
        $data['config_id'] = $config_id;
        $data['device_sn'] = $uid;
        $data['create_time'] = time();
        $result = $feed_back_Model->add($data);
        if($result){
            $this->ajaxReturn(['code'=>self::SUCC_CODE,'message'=>"感谢您的反馈"]);
        }else{
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"反馈失败，稍后请重试！"]);
        }
    }

    //判断用户是否存在   不在则添加新用户
    public function add_user(){
        $user_Model = M('user');
        $sex = I('post.sex',1,'intval');//1男 2女
        //判断是否是新用户
        $is_exist = $user_Model->where(['device_sn'=>$this->uid])->find();
        if(!$is_exist){
            $data['device_sn'] = $this->uid;
            $data['sex'] = $sex;
            $data['create_time'] = time();

            $result = $user_Model->add($data);
            if($result){
                $this->ajaxReturn(['code'=>self::SUCC_CODE]);
            }else{
                $this->ajaxReturn(['code'=>self::FAIL_CODE]);
            }
        }else{
            if($is_exist['sex']!=$sex){
                M('user')->where(['device_sn'=>$this->uid])->save(['sex'=>$sex]);
            }
            $this->ajaxReturn(['code'=>1]);
        }
    }

    //排行榜
    public function rank_list(){
        $rank_novel_Model = M('novelrank');
        $rank_Model = M('rank');
        $novel_Model = M('novel');
        $where['is_del'] = 0;
        $list =  $rank_novel_Model->where($where)->field('rank_id,novel_id')->select();
        $show_list = [];
        foreach($list as $key => $val){
            $show_list[$val['rank_id']][] = $val;
        }

        $data = [];
        foreach($show_list as $key => $val){
            $rank_info = $rank_Model->where(['id'=>$key])->field('rank_name,pic')->find();
            $name = $rank_info['rank_name'];
            $pic = $rank_info['pic'];
            if(strpos($pic,'http')!==0){
                $pic = "http://{$_SERVER['HTTP_HOST']}{$pic}";
            }
            $novel_arr = [];
            foreach($val as $k=>$v){
                $novel_arr[] = $v['novel_id'];
            }

            $novel_list = $novel_Model->where(['id'=>['in',$novel_arr]])->field('id,title')->limit(3)->select();

            $data[] = ['id'=>$key,'name'=>$name,'pic'=>$pic,'list'=>$novel_list];
        }

        $this->ajaxReturn(['code'=>self::SUCC_CODE,'data'=>$data]);
    }

    //排行榜下小说列表
    public function rank_novel_list(){
        $novel_Model = M('novel');
        $rank_novel_Model = M('novelrank');
        $rank_id = I('post.id');

        if(!isset($rank_id)){
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"参数错误，请重试"]);
        }


        $offset = I('post.offset',0,'intval');
        $limit = I('post.limit',100,'intval');
        $rank_name = M('rank')->getfieldbyid($rank_id,'rank_name');
        $where['is_del'] = 0;
        $where['rank_id'] = $rank_id;
        $rank_novel_ids = $rank_novel_Model->where($where)->limit($offset,$limit)->field('novel_id')->select();
        foreach($rank_novel_ids as $val){
            $rank_novel_arr[] = $val['novel_id'];
        }

        $list = $novel_Model->where(['id'=>['in',$rank_novel_arr],'is_del'=>0,'is_pass'=>1])->select();
        foreach($list as $key=>$val){
            $is_collect = $this->is_collect_novel($val['id']);
            if($is_collect == 0){
                $list[$key]['is_collect'] = 1;
            }else{
                $list[$key]['is_collect'] = 0;
            }

            if(!(strpos($val['cover'],'http://') === 0)){
                $list[$key]['cover'] = 'http://'.$_SERVER['HTTP_HOST'].$val['cover'];
            }
            $list[$key]['create_time'] = date('Y-m-d',$val['create_time']);
            $list[$key]['words_number'] = $this->number_to_word($val['words_number']);
            $list[$key]['collect_number'] = $this->number_to_word($val['collect_number']);
            $list[$key]['read_number'] = $this->number_to_word($val['read_number']);

            $list[$key]['label'] = $this->str_to_arr($val['label']);                      //标签

            $chapter_number = M('chapter')->where(['novel_id'=>$val['id']])->count();
            $list[$key]['chapter_number'] = $chapter_number;                      //总章数字

            //未读章节
            $is_read = M('readrecord')->where(['device_sn'=>$this->uid,'novel_id'=>$val['id']])->find();
            if($is_read){
                $novel_chapter = M('chapter')->where(['id'=>$is_read['chapter_id']])->find();
                $list[$key]['not_read_number'] = $chapter_number - $novel_chapter['novel_chapter'];
            }
        }

        $this->ajaxReturn(['code'=>self::SUCC_CODE,'rank_name'=>$rank_name,'list'=>$list?$list:[]]);
    }

    //阅读记录
    public function read_novel_list(){
        $read_Model = M('readrecord');
        $novel_Model = M('novel');
        $uid = $this->uid;
        $read_list = $read_Model->where(['device_sn'=>$uid])->select();
        $novel_arr = [];
        foreach($read_list as $val){
            $novel_arr[] = $val['novel_id'];
        }

        $read_novel_list = $novel_Model->where(['id'=>['in',$novel_arr],'is_pass'=>1])->select();

        foreach($read_novel_list as $key=>$val){
            if(!(strpos($val['cover'],'http://') === 0)){
                $read_novel_list[$key]['cover'] = 'http://'.$_SERVER['HTTP_HOST'].$val['cover'];
            }
        }
        $this->ajaxReturn(['code'=>self::SUCC_CODE,'list'=>$read_novel_list?$read_novel_list:[]]);
    }

    //猜你喜欢
    public function guess_like(){
        $read_Model = M('readrecord');
        $novel_Model = M('novel');
        $uid = $this->uid;
        $read_list = $read_Model->where(['device_sn'=>$uid])->select();
        $novel_arr = [];
        foreach($read_list as $val){
            $novel_arr[] = $val['novel_id'];
        }

        $class_list = $novel_Model->where(['id'=>['in',$novel_arr]])->field('class_id')->select();

        //阅读过的小说类型ids
        $class_arr = [];
        foreach($class_list as $val){
            $class_arr[] = $val['class_id'];
        }

        $array = array_count_values($class_arr);  // 统计数组中所有值出现的次数
        arsort($array); // 按照键值对关联数组进行降序排序
        $more_value = key($array);    //出现次数最多的值

        //猜你喜欢
        $guess_like_list = $this->order_novel_list(['class_id'=>$more_value],'read_number',6);
        foreach($guess_like_list as $key=>$val){
            if(!(strpos($val['cover'],'http://') === 0)){
                $guess_like_list[$key]['cover'] = 'http://'.$_SERVER['HTTP_HOST'].$val['cover'];
            }


            $guess_like_list[$key]['words_number'] = $this->number_to_word($val['words_number']);
            $guess_like_list[$key]['collect_number'] = $this->number_to_word($val['collect_number']);
            $guess_like_list[$key]['read_number'] = $this->number_to_word($val['read_number']);
            $guess_like_list[$key]['label'] = $this->str_to_arr($val['label']);                      //标签

            $chapter_number = M('chapter')->where(['novel_id'=>$val['id']])->count();
            $guess_like_list[$key]['chapter_number'] = $chapter_number;                      //总章数字

            //未读章节
            $is_read = M('readrecord')->where(['device_sn'=>$this->uid,'novel_id'=>$val['id']])->find();
            if($is_read){
                $novel_chapter = M('chapter')->where(['id'=>$is_read['chapter_id']])->find();
                $guess_like_list[$key]['not_read_number'] = $chapter_number - $novel_chapter['novel_chapter'];
            }
        }
        $this->ajaxReturn(['code'=>self::SUCC_CODE,'list'=>$guess_like_list]);
    }

    //添加章节到数据库
    public function add_chapter(){
        $chapter_Model = M('chapter');
        $stdin = file_get_contents('php://input');
        if(!empty($stdin)){
            $_POST = json_decode($stdin,true);
            if(empty($_POST)){
                unset($_POST);
            }
        }
        $data = $_POST;
        // $data = I('data');   //data为数组，数组项有title,content,novel_id,words_number

        $data['create_time'] = time();
        $data['update_time'] = time();

        $is_exist = $chapter_Model->where(['chap_num'=>$data['chap_num'],'novel_id'=>$data['novel_id'],'is_del'=>0])->find();
        if($is_exist){
            $this->ajaxReturn(['code'=>self::SUCC_CODE,'message'=>"此章节已存在"]);
        }

        $result = $chapter_Model->add($data);
        if($result){
            $this->ajaxReturn(['code'=>self::SUCC_CODE,'message'=>"添加小说成功"]);
        }else{
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"添加失败，稍后请重试"]);
        }
    }

    //添加小说到数据库
    public function add_novel(){
        $novel_Model = M('novel');
        $stdin = file_get_contents('php://input');
        if(!empty($stdin)){
            $_POST = json_decode($stdin,true);
            if(empty($_POST)){
                unset($_POST);
            }
        }
        $data = $_POST;
        // $data = I('post.data');  //data为数组，数组项有title，intro,author,is_finish,is_serial,fit_crowd,class_id,cover
        if(empty($data['title'])){
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"小说名不存在"]);
        }
        $is_exist = $novel_Model->where(['title'=>$data['title'],'author'=>$data['author'],'is_del'=>0])->find();
        if($is_exist){
            $this->ajaxReturn(['code'=>self::SUCC_CODE,'message'=>"此小说已存在",'novel_id'=>$is_exist['id']]);
        }

        $data['create_time'] = time();
        $data['update_time'] = time();

        $result = $novel_Model->add($data);
        if($result){
            $this->ajaxReturn(['code'=>self::SUCC_CODE,'message'=>"添加小说成功",'novel_id'=>$result]);
        }else{
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"添加失败，稍后请重试"]);
        }
    }

    //上传图片
    public function upload_pic(){
        $type = I('post.type');

        //name 值为pic
        if($_FILES['pic']['tmp_name']){
            $file_size = $_FILES['pic']["size"]; // 文件大小

            if ($file_size > 5000000) {
                $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"文件大小不能超过5M"]);
            }

            $info = CommonController::imgUpload($type);
            if(!$info){
                $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"上传图片失败，稍后请重试"]);
            }else{
                $pic = 'http://'.$_SERVER['HTTP_HOST'].'/Public/uploads/'.$info['pic']['savepath'].$info['pic']['savename'];
                $this->ajaxReturn(['code'=>self::SUCC_CODE,'message'=>"上传图片成功",'data'=>$pic]);
            }
        }else{
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"上传失败，稍后请重试"]);
        }
    }

    public function upload_pic2(){
        $type = I('post.type');
        $novel_id = I('post.novel_id',0,'intval');
        //name 值为pic
        if($_POST['file']){
            if(!file_exists(WEB_ROOT.'/Public/uploads/cover')){
                mkdir(WEB_ROOT.'/Public/uploads/cover',0777,true);
            }
            if(file_exists(WEB_ROOT.'/Public/uploads/cover/'.$novel_id.'.jpg')){
                $this->ajaxReturn(['code'=>self::SUCC_CODE,'message'=>"上传图片成功",'data'=>'']);
            }
            file_put_contents(WEB_ROOT.'/Public/uploads/cover/'.$novel_id.'.jpg',$_POST['file']);
            // $file_size = $_FILES['pic']["size"]; // 文件大小

            // if ($file_size > 5000000) {
            //     $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"文件大小不能超过5M"]);
            // }

            // $info = CommonController::imgUpload($type);
            $filename = '/Public/uploads/cover/'.$novel_id.'.jpg';
            $net_pic = 'http://'.$_SERVER['HTTP_HOST'].$filename;
            $pic = $filename;
            if($pic && $novel_id){
                M('novel')->where(['id'=>$novel_id])->save(['cover'=>$pic]);
            }
            $this->ajaxReturn(['code'=>self::SUCC_CODE,'message'=>"上传图片成功",'data'=>$net_pic]);
            // if(!$info){
            //     $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"上传图片失败，稍后请重试"]);
            // }else{
            //     $net_pic = 'http://'.$_SERVER['HTTP_HOST'].'/Public/uploads/'.$info['pic']['savepath'].$info['pic']['savename'];
            //     $pic = '/Public/uploads/'.$info['pic']['savepath'].$info['pic']['savename'];
            //     if($pic && $novel_id){
            //         M('novel')->where(['id'=>$novel_id,'cover'=>['eq','']])->save(['cover'=>$pic]);
            //     }
            //     $this->ajaxReturn(['code'=>self::SUCC_CODE,'message'=>"上传图片成功",'data'=>$net_pic]);
            // }
        }else{
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"上传失败，稍后请重试"]);
        }
    }

    //广告列表
    public function ad_list(){
        $ad_Model = M('ad');

        $where['is_del'] = 0;
        $order['order'] = 'asc';
        $ad_list = $ad_Model->where($where)->order($order)->select();
        foreach($ad_list as $key=>$val){
            if(!(strpos($val['pic'],'http://') === 0)){
                $ad_list[$key]['pic'] = 'http://'.$_SERVER['HTTP_HOST'].$val['pic'];
            }
        }
        $this->ajaxReturn(['code'=>self::SUCC_CODE,'list'=>$ad_list?$ad_list:[]]);
    }

    //今日推荐
    public function recommend_today(){
        $Novel_Model = M('novel');
        $where = [];

        $where['is_del'] = 0;
        $where['is_recommend'] = 1;
        $where['is_pass'] = 1;

        $list = $Novel_Model->where($where)->order('recommend_time desc')->limit(10)->select();
        foreach($list as $key=>$val){
            if(!(strpos($val['cover'],'http://') === 0)){
                $list[$key]['cover'] = 'http://'.$_SERVER['HTTP_HOST'].$val['cover'];
            }

            $list[$key]['words_number'] = $this->number_to_word($val['words_number']);
            $list[$key]['collect_number'] = $this->number_to_word($val['collect_number']);
            $list[$key]['read_number'] = $this->number_to_word($val['read_number']);
            $list[$key]['label'] = $this->str_to_arr($val['label']);                      //标签

            $chapter_number = M('chapter')->where(['novel_id'=>$val['id']])->count();
            $list[$key]['chapter_number'] = $chapter_number;                      //总章数字

            //未读章节
            $is_read = M('readrecord')->where(['device_sn'=>$this->uid,'novel_id'=>$val['id']])->find();
            if($is_read){
                $novel_chapter = M('chapter')->where(['id'=>$is_read['chapter_id']])->find();
                $list[$key]['not_read_number'] = $chapter_number - $novel_chapter['novel_chapter'];
            }
        }

        $this->ajaxReturn(['code'=>self::SUCC_CODE,'list'=>$list?$list:[]]);
    }


    //分类推荐
    public function recommend_class(){
        $novel_Model = M('novel');
        $class_Model = M('class');

        $where['is_del'] = 0;
        $where['is_recommend'] = 1;
        $list = $novel_Model->where($where)->field('class_id')->group('class_id')->select();


        //小说类型ids
        $class_arr = [];
        foreach($list as $val){
            $class_arr[] = $val['class_id'];
        }

        $class_list = $class_Model->where(['id'=>['in',$class_arr]])->field('id,class_name,cover_pic')->select();
        foreach($class_list as $key => $val){
            $class_list[$key]['novel_number'] = $this->class_novel_number($val['id']);

            if($val['cover_pic']){
                if(!(strpos($val['cover_pic'],'http://') === 0)){
                    $class_list[$key]['cover_pic'] = 'http://'.$_SERVER['HTTP_HOST'].$val['cover_pic'];
                }
            }
        }
        $this->ajaxReturn(['code'=>self::SUCC_CODE,'list'=>$class_list?$class_list:[]]);
    }

    //文章列表
    public function article_list(){
        $article_Model = M('article');
        $where = [];

        //关键字搜索
        $keyword = trim(I('post.keyword'));
        if($keyword != ''){
            $where['title'] = ['like',"%$keyword%"];
        }

        $where['is_del'] = 0;

        $offset = I('post.offset',0,'intval');
        $limit = I('post.limit',100,'intval');

        $list = $article_Model->where($where)->limit($offset,$limit)->select();
        foreach($list as $key=>$val){

            if(!(strpos($val['pic'],'http://') === 0)){
                $list[$key]['pic'] = 'http://'.$_SERVER['HTTP_HOST'].$val['pic'];
            }
        }

        $this->ajaxReturn(['code'=>self::SUCC_CODE,'list'=>$list?$list:[]]);
    }


    //判断用户是否阅读过某小说
    public function is_read_one_novel(){
        $novel_id = I('post.id');
        $is_read = $this->is_read_novel($novel_id);
        if($is_read == 0){
            $this->ajaxReturn(['code'=>self::SUCC_CODE]);
        }else{
            $this->ajaxReturn(['code'=>self::FAIL_CODE]);
        }
    }

    //热门搜索接口
    public function hot_reach(){
        $Novel_Model = M('novel');
        $where['is_del'] = 0;

        $order_by['search_number'] = 'desc';

        $list = $Novel_Model->where($where)->order($order_by)->field('id,title')->limit(10)->select();

        $this->ajaxReturn(['code'=>self::SUCC_CODE,'list'=>$list?$list:[]]);
    }

    //某分类下小说列表
    public function class_novel_list(){
        $novel_Model = M('novel');
        $class_id = I('post.class_id');

        if(!isset($class_id)){
            $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"参数错误，请重试"]);
        }
        $class_name = M('class')->getfieldbyid($class_id,'class_name');
        $where['class_id'] = $class_id;
        $where['is_del'] = 0;
        $where['is_pass'] = 1;


        $offset = I('post.offset',0,'intval');
        $limit = I('post.limit',100,'intval');

        $list = $novel_Model->where($where)->limit($offset,$limit)->select();
        foreach($list as $key=>$val){
            $is_collect = $this->is_collect_novel($val['id']);
            if($is_collect == 0){
                $list[$key]['is_collect'] = 1;
            }else{
                $list[$key]['is_collect'] = 0;
            }

            if(!(strpos($val['cover'],'http://') === 0)){
                $list[$key]['cover'] = 'http://'.$_SERVER['HTTP_HOST'].$val['cover'];
            }
            $list[$key]['create_time'] = date('Y-m-d',$val['create_time']);
            $list[$key]['words_number'] = $this->number_to_word($val['words_number']);
            $list[$key]['collect_number'] = $this->number_to_word($val['collect_number']);
            $list[$key]['read_number'] = $this->number_to_word($val['read_number']);

            $list[$key]['label'] = $this->str_to_arr($val['label']);                      //标签
            $chapter_number = M('chapter')->where(['novel_id'=>$val['id']])->count();
            $list[$key]['chapter_number'] = $chapter_number;                      //总章数字

            //未读章节
            $is_read = M('readrecord')->where(['device_sn'=>$this->uid,'novel_id'=>$val['id']])->find();
            if($is_read){
                $novel_chapter = M('chapter')->where(['id'=>$is_read['chapter_id']])->find();
                $list[$key]['not_read_number'] = $chapter_number - $novel_chapter['novel_chapter'];
            }
        }

        $this->ajaxReturn(['code'=>self::SUCC_CODE,'class_name'=>$class_name,'list'=>$list?$list:[]]);
    }

    //常见问题列表
    public function problem_list(){
        $problem_Model = M('problem');
        $problem_list = $problem_Model->order(['sort asc'])->select();
        $this->ajaxReturn(['code'=>self::SUCC_CODE,'list'=>$problem_list?$problem_list:[]]);
    }

    //用户协议
    public function user_agreement(){
        $config_Model = M('system_config');
        $agreement = $config_Model->where(['key'=>"USER_AGREEMENT"])->getField('value');

        $agreement = htmlspecialchars_decode($agreement);
        $this->ajaxReturn(['code'=>self::SUCC_CODE,'data'=>$agreement]);
    }

    //小说筛选项
    public function search_class_item(){
        $class_Model = M('search_class');
        $item_Model = M('search_item');

        $list = [];
        $item_list = $item_Model->where(['is_del'=>0])->field('id,search_class_id,name,field')->select();
        foreach($item_list as $key => $val){
            $list[$val['search_class_id']][] = $val;
        }

        $show_list = [];
        foreach($list as $key=>$val){
            $name = $class_Model->where(['id'=>$key,'is_del'=>0])->getfield('name');
            $show_list[] = [
                'name'=>$name,
                'val'=>$val
            ];
        }

        $this->ajaxReturn(['code'=>self::SUCC_CODE,'list'=>$show_list?$show_list:[]]);
    }

}
